import { Badge, Descriptions, Image, Tag, message, Tooltip, Pagination, Table, Skeleton, Modal } from 'antd';
import "../../index.css"
import { useEffect, useState } from 'react';
import { BanGoods, GetGoodsOrderDetails, GetInventorys, GetSingleGoods, ShelveGoods } from '../../api/goods';
import { useNavigate, useParams } from 'react-router-dom';
import dayjs from 'dayjs';
import { Admin_GetSingleSupplier, Admin_GetSupplierOrders, GetOrderDetails, GetSupplierGoods, GetSupplierStatistics } from '../../api/supplier';
import { GetSupplierOrderDetails } from '../../api/home';


//供应商详情页面
const SupplierDetail = () => {
    document.info = [
        {
            title: "供应商管理详情",
            url: "/supplier/detail"
        },
        {
            title: "供应商管理-主页",
            url: "/supplier",
        }
    ]
    //详情数据
    const [detail, setDetail] = useState({
    });

    const [load, setLoad] = useState({
        //销售订单单个详情表格加载
        load_a: false,
        //销售订单单个详情表格骨架屏
        isFirst_a: true,
    })
    //销售数据模态框
    const [open_a, setOpen_a] = useState(false);

    //销售订单详情数据
    const [orderDetailTable, setOrderDetailData] = useState([]);

    //获取销售数据详情
    const [goodsOrder, setGoodsOrder] = useState({
        page: 1,
        limit: 10,
        total: 0,
        data: [],
        loading: false,
    });



    //获取库存数据
    const [inventorys, setInventorys] = useState({
        page: 1,
        limit: 10,
        total: 0,
        data: [],
        loading: false,
    });

    //获取路径id
    const { id } = useParams();

    const navigate = useNavigate();
    //骨架屏
    const [isFirst, setFirst] = useState(true);





    //供应商详情按钮
    const supplierDetail = (props) => {
        console.log(props);
    }



    const columns_inventorys = [
        {
            title: '序号',
            dataIndex: 'Index',
            key: 'Index',
            width: 60
        },
        {
            title: '图片',
            dataIndex: 'photo',
            key: 'photo',
            width: 80,
            render: (text) => <img src={text} width={60} alt="" className="good-photo" />
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: 80,
            render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 80,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        cursor: 'pointer',

                    }
                }
            },
        },

        {
            title: '供应商',
            dataIndex: 'supplier',
            key: 'supplier',
            width: 80,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 80,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',
                        cursor: 'pointer',

                    }
                }
            },
            render: (text) => (
                <div>
                    {text == null ? <Tag color="red" bordered={false} className="danger-tag">直营</Tag> :
                        <span><Tooltip placement="topLeft" title={text}>{text.length > 4 ? text.substring(0, 4) + "..." : text}</Tooltip></span>}
                </div>
            ),
        },
        {
            title: '单价',
            dataIndex: 'price',
            key: 'price',
            width: 90,
            onCell: () => {
                return {
                    style: {
                        maxWidth: 120,
                        overflow: 'hidden',
                        whiteSpace: 'nowrap',
                        textOverflow: 'ellipsis',

                    }
                }
            },
            render: (text) => (
                <div><Tag color="red" className="danger-tag" bordered={false}>￥ {text}</Tag></div>
            ),
        },
        {
            title: '库存总数',
            dataIndex: 'inventory',
            key: 'inventory',
            width: 90,
            render: (text) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text}</Tag></div>
            ),
        },
        {
            title: '销量',
            dataIndex: 'sales',
            key: 'sales',
            width: 90,
            render: (text, hang) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text}</Tag></div>
            ),
        },
        {
            title: '剩余库存',
            dataIndex: 'inventory',
            key: 'inventory',
            width: 90,
            render: (text, hang) => (
                <div><Tag color="blue" className="primary-tag" bordered={false}>{text - hang.sales}</Tag></div>
            ),
        },
        {
            title: '上架',
            dataIndex: 'isShelve',
            key: 'isShelve',
            width: 90,
            render: (text) => (
                <div> {text == 0 ? <Tag color="warning" className="warning-tag" bordered={false}>否</Tag> : <Tag color="success" className="success-tag" bordered={false}>是</Tag>}</div>
            ),
        },
        {
            title: '禁用',
            dataIndex: 'isBan',
            key: 'isBan',
            width: 90,
            render: (text) => (
                <div> {text == 0 ? <Tag color="success" className="success-tag" bordered={false}>否</Tag> : <Tag color="red" className="danger-tag" bordered={false}>是</Tag>}</div>
            ),
        },
        {
            title: '资质文件',
            dataIndex: 'isQualifications',
            key: 'isQualifications',
            width: 90,
            render: (text) => (
                <div> {text == 0 ? <Tag color="warning" bordered={false}>{text}</Tag> : <Tag color="success" className="success-tag" bordered={false}>{text}</Tag>}</div>
            ),
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            fixed: "right",
            width: 325,
            render: (text, hang) => (
                <div style={{ width: 325 }}>
                    <div style={{ marginLeft: "5px" }} className="success-cell btn" size="small" onClick={() => { goodDetail(hang.id) }}>详情</div>
                    <div type="primary" className="primary btn" style={{ marginLeft: "5px" }} onClick={() => { goZiZhi(hang.id) }}>资质</div>

                    <MyButton hang={hang}></MyButton>
                    {hang.isBan == 0 ?
                        <div className="danger btn" onClick={() => { methods.banGoods(hang, 1) }} >禁用</div>
                        : <div className="success btn" onClick={() => { methods.banGoods(hang, 0) }}>启用</div>}


                </div>
            )
        },

    ];

    //下架/上架按钮
    const MyButton = (hang) => {
        // if (hang.hang.inventory === 0 && hang.hang.sales === 0 && hang.hang.isShelve === 0 || hang.hang.isBan === 1) {
        //     return
        // } else {
        if (hang.hang.isShelve === 0) {
            return <div className="success btn" onClick={() => { methods.shelveChange(hang.hang, 1) }}>上架</div>
        } else {
            return <div className="warning btn" onClick={() => { methods.shelveChange(hang.hang, 0) }}>下架</div>
        }
        // }
    }


    //跳转详情
    const goodDetail = (props) => {
        console.log(props);
        navigate(`/goods/detail/${props}`);
    }

    const goZiZhi = (props) => {
        navigate(`/goods/qualifications/${props}`);
    }


    //获取单个供应商数据
    const getSingleGoods = async () => {
        const res = await Admin_GetSingleSupplier({ id: id });
        if (res?.result === 0) {
            setDetail(res.data);
        } else {
            message.error(res?.message);
        }
        return true

    }


    //获取销售订单表格数据
    const getSupplierOrderDetails = async () => {
        const res = await Admin_GetSupplierOrders({
            id: id,
            page: goodsOrder.page,
            limit: goodsOrder.limit,
            key: ""
        });

        if (res?.result === 0) {
            res.data.data.map((d, i) => (d.Index = i + 1));
            setGoodsOrder((goodsOrder) => ({ ...goodsOrder, data: res.data.data, total: res.data.total, loading: false }));

        } else {
            message.error(res?.message);
            setGoodsOrder((goodsOrder) => ({ ...goodsOrder, loading: false }));

        }
        return true
    }


    //获取商品列表数据
    const getSupplierGoods = async () => {
        const res = await GetSupplierGoods({
            id: id,
            page: inventorys.page,
            data: inventorys.limit
        });
        if (res?.result === 0) {
            res.data.data.map((d, i) => (d.Index = i + 1))
            setInventorys((inventorys) => ({ ...inventorys, data: res.data.data, total: res.data.total, loading: false }));

        } else {
            message.error(res?.message);
            setInventorys((inventorys) => ({ ...inventorys, loading: false }));

        }
        return true
    }

    //初始数据渲染
    useEffect(() => {
        const closeFirst = async () => {
            // let res_a = await getSingleGoods();
            // let res_b = await getSupplierOrderDetails();
            // let res_c = await getSupplierGoods();
            // if (res_a && res_b && res_c) {
            //     setFirst(false)
            // } else {
            //     message.error("数据错误")
            // }
            Promise.allSettled([getSingleGoods(), getSupplierOrderDetails(), getSupplierGoods()]).then((res) => {
                const result = res.map((d) => d.value == true);
                if (result) {
                    setFirst(false)
                } else {
                    message.error("数据有误");
                    setFirst(false)
                }
            })
        }
        closeFirst();
    }, []);




    //监听销售订单数据
    useEffect(() => {
        setGoodsOrder((goodsOrder) => ({ ...goodsOrder, loading: true }));
        getSupplierOrderDetails();
    }, [goodsOrder.page, goodsOrder.limit, goodsOrder.total]);


    //监听商品列表数据
    useEffect(() => {
        setInventorys((inventorys) => ({ ...inventorys, loading: true }));
        getSupplierGoods();
    }, [inventorys.page, inventorys.limit, inventorys.total]);


    const methods = {
        //订单详情的模态框关闭事件触发
        hiddenModel: () => {
            setOpen_a(false)
            setLoad((load) => ({ ...load, isFirst_a: true }));
        },
        //销售订单点击详情按钮查询单个订单详情
        getOrderDetails: async (id) => {
            const res = await GetOrderDetails({ id: id });
            if (res.result === 0) {
                res.data.map((d, i) => d.Index = i + 1)
                setOrderDetailData(res.data);
                setLoad((load) => ({ ...load, isFirst_a: false }));
            } else {
                message.error(res.message);
                setOpen_a(false);
            }
        },
        //销售订单详情按钮 模态框打开并加载数据
        orderDetail: (props) => {
            setOpen_a(true);
            methods.getOrderDetails(props);
        },

        //禁用/启用 1/0
        banGoods: async (props, num) => {
            setInventorys((inventorys) => ({ ...inventorys, loading: true }));
            const res = await BanGoods({ ids: [props.id], isBan: num });
            if (res.result === 0) {
                message.success("操作成功");
                getSupplierGoods();
            } else {
                message.error(res.message);
                setInventorys((inventorys) => ({ ...inventorys, loading: false }));
            }
        },
        //销售订单分页方法
        ordersPageChange: (value) => {
            setGoodsOrder((goodsOrder) => ({ ...goodsOrder, page: value }))
        },
        //商品列表分页方法
        shopListChange: (value) => {
            setInventorys(() => ({ ...inventorys, page: value }))
        },
        //上下架按钮事件
        shelveChange: async (props, num) => {
            setInventorys((inventorys) => ({ ...inventorys, loading: true }));
            const res = await ShelveGoods({ ids: [props.id], isShelve: num });
            if (res.result === 0) {
                message.success("操作成功");
                getSupplierGoods();
            } else {
                message.error(res.message);
            }
        }
    }

    const data = {

        //销售订单的详情的表格
        columns_orderSon: [
            {
                title: '序号',
                dataIndex: 'Index',
                key: 'Index',
                with: 20
            },
            {
                title: '图片',
                dataIndex: 'photo',
                key: 'photo',
                render: (text) => <img style={{ width: 60, borderRadius: 5 }} src={text}></img>

            },
            {
                title: '商品名称',
                dataIndex: 'goodsName',
                key: 'goodsName'
            },
            {
                title: '类型',
                dataIndex: 'goodsType',
                key: 'goodsType',
                render: (text) => {
                    return <div>{text === "" || text === null ? "其他" : text}</div>
                }
            },

            {
                title: '供应商',
                dataIndex: 'merchant',
                key: 'merchant',
                ellipsis: {
                    showTitle: false,
                },
                width: 120,
                render: (text) => (
                    <Tooltip placement="topLeft" title={text}>
                        <Tag color='blue' bordered={false} className='primary-tag'>{text}</Tag>
                    </Tooltip>
                )

            },
            {
                title: '单价',
                dataIndex: 'price',
                key: 'price',
                ellipsis: {
                    showTitle: false,
                },
                width: 120,
                render: (text) => <Tooltip placement="topLeft" title={text}>
                    <Tag color='blue' bordered={false} className='primary-tag'>￥ {text}</Tag>
                </Tooltip>
            },
            {
                title: '数量',
                dataIndex: 'number',
                key: 'number',
                render: (text) => <Tag color='blue' bordered={false} className='primary-tag'>{text}</Tag>
            },

            {
                title: '小计',
                dataIndex: 'money',
                key: 'money',
                ellipsis: {
                    showTitle: false,
                },
                width: 120,
                render: (text) => <Tooltip placement="topLeft" title={text}>
                    <Tag color='red' bordered={false} className='danger-tag'>￥ {text}</Tag>
                </Tooltip>
            },
        ],
        // 销售订单数据表格
        columns_goodsOrder: [
            {
                title: '序号',
                dataIndex: 'Index',
                key: 'Index',
                width: 50,
            },
            {
                title: '详情号',
                dataIndex: 'id',
                key: 'id',
                ellipsis: {
                    showTitle: false,
                },
                with: 80,
                render: (text) => (<Tooltip placement="topLeft" title={text}>{text}</Tooltip>),

            },
            {
                title: '供应商',
                dataIndex: 'supplier',
                key: 'supplier',
                width: 120,
                ellipsis: {
                    showTitle: false,
                },
                render: (text) => <Tooltip placement="topLeft" title={text}><Tag color='blue' bordered={false} className='primary-tag'>{text}</Tag></Tooltip>

            },
            {
                title: '商户',
                dataIndex: 'merchant',
                key: 'merchant',
                // with:50,
                ellipsis: {
                    showTitle: false,
                },
                render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>

            },

            {
                title: '商品',
                dataIndex: 'goodsNames',
                key: 'goodsNames',
                ellipsis: {
                    showTitle: false,
                },
                render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
            },
            {
                title: '数量',
                dataIndex: 'goodsCount',
                key: 'goodsCount',

            },
            {
                title: '金额',
                dataIndex: 'money',
                key: 'money',
                ellipsis: {
                    showTitle: false,
                },

                render: (text) => <Tooltip placement="topLeft" title={text}>
                    <Tag color='red' bordered={false} className='danger-tag'>￥ {text}</Tag>
                </Tooltip>
            },
            {
                title: '时间',
                dataIndex: 'time',
                key: 'time',
                // with:50,
                ellipsis: {
                    showTitle: false,
                },
                render: (text) => <Tooltip placement="topLeft" title={text}>{text}</Tooltip>
            },

            {
                title: '操作',
                dataIndex: '',
                key: '',
                width: 155,
                fixed: "right",
                render: (text, hang) => (
                    <div style={{ width: 155 }}>
                        <div style={{ marginLeft: "5px" }} className="primary-cell btn" size="small" onClick={() => { methods.orderDetail(hang.id) }}>详情</div>
                    </div>
                )
            },

        ],
        //描述列表
        items: [
            {
                key: '1',
                label: '企业名称',
                children: <Tag color='blue' bordered={false} className='primary-tag'>
                    {detail.enterpriseName}
                </Tag>
            },
            {
                key: '2',
                label: '负责人',
                children: <Tag color='blue' bordered={false} className='primary-tag'>
                    {detail.name}
                </Tag>
            },
            {
                key: '3',
                label: '账号',
                children: <Tag color='blue' bordered={false} className='primary-tag'>
                    {detail.account}
                </Tag>
            },
            {
                key: '4',
                label: '添加时间',
                children: <Tag color='blue' bordered={false} className='primary-tag'>
                    {detail.time}
                </Tag>
            },
            {
                key: '5',
                label: '激活',
                children: detail.isActive == 1 ?
                    <Tag color='green' className='success-tag' bordered={false}>是</Tag> :
                    <Tag color='red' className='danger-tag' bordered={false}>否</Tag>
            },
            {
                key: '6',
                label: '禁用',
                children: detail.isBan == 1 ?
                    <Tag color='red' className='danger-tag' bordered={false}>是</Tag> :
                    <Tag color='green' className='success-tag' bordered={false}>否</Tag>
            },
            {
                key: '7',
                label: '订单',
                children: <Tag color='blue' bordered={false} className='primary-tag'>{detail.orderCount}</Tag>
            },
            {
                key: '8',
                label: '完成订单',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.completeOrderCount}</Tag>
            },
            {
                key: '9',
                label: '销售金额',
                children: <Tag color='red' className='danger-tag' bordered={false}>¥ {detail.money}</Tag>
            },

            {
                key: '10',
                label: '成交金额',
                children: <Tag color='red' className='danger-tag' bordered={false}>¥ {detail.currMoney}</Tag>

            },
            {
                key: '11',
                label: '已发货订单',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.sendCount}</Tag>
            },
            {
                key: '12',
                label: '已收货订单',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.receiveCount}</Tag>
            },
            {
                key: '13',
                label: '商品数量',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.goodsCategory}</Tag>
            },
            {
                key: '14',
                label: '未上架商品',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.notShelveCount}</Tag>
            },
            {
                key: '15',
                label: '商品总库存',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.inventory} 件</Tag>
            },
            {
                key: '16',
                label: '已取消订单',
                children: <Tag color='blue' className='primary-tag' bordered={false}>{detail.cancelOrderCount}</Tag>
            },
            {
                key: '17',
                label: '取消金额',
                children: <Tag color='red' className='danger-tag' bordered={false}>¥ {detail.cancelMoney}</Tag>
                ,span:2
            },
            {
                key: '18',
                label: '企业logo',
                children:detail.logo===null?<div style={{height:100,width:100,background:"#eee"}}></div>:<Image src={detail.logo} width={100}> </Image>
            },
            {
                key: '19',
                label: '企业图片',
                  children:detail.photo===null?<div style={{height:100,width:100,background:"#eee"}}></div>:<Image src={detail.photo} width={100}> </Image>
            },
            {
                key: '20',
                label: '企业资质',
                 children:detail.qualification===null?<div style={{height:100,width:100,background:"#eee"}}></div>:<Image src={detail.qualification} width={100}> </Image>
            },

        ]
    }




    return (
        <div className="Containers good_detailIndex " style={{ padding: 0 }}>
            <Skeleton active loading={isFirst} paragraph={{ rows: 15 }}>
                <div className='pds'>
                    <Descriptions title="供应商详情" layout="vertical" bordered items={data.items} />
                </div>

                <div className='data_title'>
                    <div className='data_title_left'>
                        <div className='data_title_name goodOrder-title'>
                            销售订单
                        </div>
                    </div>

                    <div className='data_title_right'>


                    </div>

                </div>

                <div className='pds'>
                    <Table dataSource={goodsOrder.data} columns={data.columns_goodsOrder} bordered pagination={false} loading={goodsOrder.loading}
                        style={{ marginTop: "5px" }}
                        scroll={{
                            y: 500
                        }}
                    />


                    <Modal
                        title="订单详情"
                        okButtonProps={false}
                        open={open_a}
                        onOk={() => methods.hiddenModel()}
                        onCancel={() => methods.hiddenModel()}
                        width={1200}
                        footer={null}
                    >
                        <Skeleton active loading={load.isFirst_a} paragraph={{ rows: 5 }}>
                            <Table dataSource={orderDetailTable} columns={data.columns_orderSon} bordered pagination={false} loading={load.load_a}
                                style={{ marginTop: "5px" }}
                                scroll={{
                                    y: 500
                                }}
                            />
                        </Skeleton>



                    </Modal>


                    <div className="page-layout">
                        <Pagination defaultCurrent={1} total={goodsOrder.total} onChange={(value) => { methods.ordersPageChange(value) }} />
                    </div>
                </div>



                <div className='data_title'>
                    <div className='data_title_left'>
                        <div className='data_title_name data_title_goodlist'>
                            商品列表
                        </div>
                    </div>

                    <div className='data_title_right'>


                    </div>

                </div>


                <div className='pds'>
                    <Table dataSource={inventorys.data} columns={columns_inventorys} bordered pagination={false} loading={inventorys.loading}
                        style={{ marginTop: "5px" }}
                        scroll={{
                            y: 500,
                            x: 1200
                        }}
                    />


                    <div className="page-layout">
                        <Pagination defaultCurrent={1} total={inventorys.total} onChange={(value) => { methods.shopListChange(value) }} />
                    </div>
                </div>
            </Skeleton>

        </div>
    )
}


export default SupplierDetail